//
// Created on 2023/12/21.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#include "pcm_generator.h"
#include <dirent.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <errno.h>
#include <string.h>
#include <string>

#define SAMPLE_RATE 44100 // Sample rate in Hz
#define DURATION 1        // Duration of the sine wave in seconds
#define AMPLITUDE 0.5     // Amplitude of the sine wave
#define FREQUENCY 800.0   // Frequency of the sine wave in Hz
#define NUM_CHANNELS 1    // Number of audio channels (1 for mono, 2 for stereo)

#define FILE_PATH "/data/storage/el2/base/haps/entry/files/sine_wave.wav"
const char *root = "/data/storage/el2/base/haps/entry/files/";

void iterateFolder() {
    DIR *directory;
    struct dirent *entry;

    // Open the directory
    directory = opendir(root);
    
    if (errno != 0) {
        std::string a = strerror(errno);
        closedir(directory);
        return;
    }
    // Check if the directory opened successfully
    if (directory == NULL) {
        perror("Unable to open directory");
        return;
    }

    // Read entries from the directory
    while ((entry = readdir(directory)) != NULL) {
        // Print the name of each file in the directory
        printf("%s\n", entry->d_name);
    }

    // Close the directory
    closedir(directory);
}

int generatePCM(int frequency) {
//    iterateFolder();
    
    FILE *wav_file;
    int16_t sample;
    double t, dt;

    // Open the WAV file for writing
    wav_file = fopen(FILE_PATH, "wb");
    
    if (!wav_file) {
        fprintf(stderr, "Error opening WAV file for writing\n");
        return 1;
    }

    // Calculate the time step (inverse of sample rate)
    dt = 1.0 / SAMPLE_RATE;

    const uint32_t chunkSize = 16;
    const uint16_t audioFormat = 1;
    const uint16_t numChannels = NUM_CHANNELS;
    const uint32_t sampleRate = SAMPLE_RATE;
    const uint32_t byteRate = SAMPLE_RATE * NUM_CHANNELS * sizeof(int16_t);
    const uint16_t blockAlign = NUM_CHANNELS * sizeof(int16_t);
    const uint16_t bitsPerSample = 16;

    // Write WAV file header
//    fprintf(wav_file, "RIFF----WAVEfmt ");  // Chunk ID and format
//    fwrite(&chunkSize, 4, 1, wav_file);     // Chunk size (16 for PCM)
//    fwrite(&audioFormat, 2, 1, wav_file);   // Audio format (1 for PCM)
//    fwrite(&numChannels, 2, 1, wav_file);   // Number of channels
//    fwrite(&sampleRate, 4, 1, wav_file);    // Sample rate
//    fwrite(&byteRate, 4, 1, wav_file);      // Byte rate
//    fwrite(&blockAlign, 2, 1, wav_file);    // Block align
//    fwrite(&bitsPerSample, 2, 1, wav_file); // Bits per sample
//
//    fprintf(wav_file, "data----"); // Data sub-chunk

    // Generate and write sine wave samples
//    for (t = 0; t < DURATION; t += dt) {
//        sample = AMPLITUDE * (int16_t)(32767.0 * sin(2.0 * M_PI * frequency * t));
//        fwrite(&sample, sizeof(int16_t), 1, wav_file);
//    }

    int count = 0;
//    int index = 0;
//    int arr[1000];
//    for (int i = 0; i < 1000; i++) {
//        arr[i] = 0;
//    }
    while (1) {
        sample = AMPLITUDE * (int16_t)(32767.0 * sin(2.0 * M_PI * frequency * t));
        fwrite(&sample, sizeof(int16_t), 1, wav_file);
//        arr[index] = sample;
        // Update time
        t += dt;

        // Reset time when one period is completed
        if (t >= 1.0 / frequency) {
            count++;
            if (count > 1000) {
                break;
            }
            t -= 1.0 / frequency;
        }
//        index++;
    }
    
    // Close the WAV file
    fclose(wav_file);
    
    return 0;
}